<?php

    class KoreaImageController extends WebController
    {
        public $pageTitle = 'Tạo ảnh hàn quốc';

        /**
        * @return array action filters
        */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete', // we only allow deletion via POST request
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',  // allow all users to perform 'index' and 'view' actions
                    'actions'=>array(''),
                    'users'=>array('*'),
                ),
                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions'=>array('index'),
                    'users'=>array('@'),
                ),
                array('deny',  // deny all users
                    'users'=>array('*'),
                ),
            );
        }


        private function _getFrameData($frame_key = NULL){
            $frames = array(

                '31' => array(
                    'w' => 720,
                    'h' => 488,
                    'frames' => array(
                        array(
                            'w' => 303,
                            'h' => 288,

                            'x' => 30,
                            'y' => 23,
                        ),
                        array(
                            'w' => 296,
                            'h' => 365,

                            'x' => 384,
                            'y' => 36,
                        ),
                    )
                ),
                '30' => array(
                    'w' => 720,
                    'h' => 960,
                    'frames' => array(
                        array(
                            'w' => 602,
                            'h' => 751,

                            'x' => 43,
                            'y' => 74,
                        )
                    )
                ),
                '29' => array(
                    'w' => 720,
                    'h' => 540,
                    'frames' => array(
                        array(
                            'w' => 433,
                            'h' => 428,

                            'x' => 154,
                            'y' => 40,
                        )
                    )
                ),
                '28' => array(
                    'w' => 720,
                    'h' => 514,
                    'frames' => array(
                        array(
                            'w' => 556,
                            'h' => 365,

                            'x' => 81,
                            'y' => 96,
                        )
                    )
                ),
                '27' => array(
                    'w' => 720,
                    'h' => 540,
                    'frames' => array(
                        array(
                            'w' => 492,
                            'h' => 492,

                            'x' => 123,
                            'y' => 22,
                        )
                    )
                ),
                '26' => array(
                    'w' => 720,
                    'h' => 450,
                    'frames' => array(
                        array(
                            'w' => 362,
                            'h' => 300,

                            'x' => 178,
                            'y' => 70,
                        )
                    )
                ),
                '25' => array(
                    'w' => 720,
                    'h' => 480,
                    'frames' => array(
                        array(
                            'w' => 524,
                            'h' => 412,

                            'x' => 148,
                            'y' => 35,
                        )
                    )
                ),
                '24' => array(
                    'w' => 720,
                    'h' => 540,
                    'frames' => array(
                        array(
                            'w' => 410,
                            'h' => 244,

                            'x' => 24,
                            'y' => 274,
                        ),
                        array(
                            'w' => 403,
                            'h' => 241,

                            'x' => 296,
                            'y' => 33,
                        )
                    )
                ),
                '23' => array(
                    'w' => 720,
                    'h' => 514,
                    'frames' => array(
                        array(
                            'w' => 497,
                            'h' => 358,

                            'x' => 112,
                            'y' => 96,
                        )
                    )
                ),
                '22' => array(
                    'w' => 720,
                    'h' => 540,
                    'frames' => array(
                        array(
                            'w' => 585,
                            'h' => 429,

                            'x' => 60,
                            'y' => 0,
                        )
                    )
                ),
                '21' => array(
                    'w' => 720,
                    'h' => 540,
                    'frames' => array(
                        array(
                            'w' => 198,
                            'h' => 279,
                            'rotate' => -25,
                            'x' => 217,
                            'y' => 200,
                        ),
                        array(
                            'w' => 200,
                            'h' => 272,
                            'rotate' => -22,
                            'x' => 19,
                            'y' => 19,
                        ),
                        array(
                            'w' => 199,
                            'h' => 272,
                            'rotate' => 21,
                            'x' => 420,
                            'y' => 30,
                        ),
                    )
                ),
                '20' => array(
                    'w' => 720,
                    'h' => 483,
                    'frames' => array(
                        array(
                            'w' => 312,
                            'h' => 296,

                            'x' => 72,
                            'y' => 148,
                        ),
                        array(
                            'w' => 279,
                            'h' => 265,

                            'x' => 391,
                            'y' => 51,
                        )
                    )
                ),
                '19' => array(
                    'w' => 720,
                    'h' => 515,
                    'frames' => array(
                        array(
                            'w' => 649,
                            'h' => 488,

                            'x' => 0,
                            'y' => 27,
                        )
                    )
                ),
                '18' => array(
                    'w' => 720,
                    'h' => 480,
                    'frames' => array(
                        array(
                            'w' => 399,
                            'h' => 336,

                            'x' => 30,
                            'y' => 30,
                        )
                    )
                ),
                '17' => array(
                    'w' => 720,
                    'h' => 513,
                    'frames' => array(
                        array(
                            'w' => 316,
                            'h' => 371,

                            'x' => 204,
                            'y' => 89,
                        )
                    )
                ),
                '16' => array(
                    'w' => 720,
                    'h' => 480,
                    'frames' => array(
                        array(
                            'w' => 560,
                            'h' => 366,

                            'x' => 113,
                            'y' => 65,
                        )
                    )
                ),
                '15' => array(
                    'w' => 720,
                    'h' => 540,
                    'frames' => array(
                        array(
                            'w' => 426,
                            'h' => 406,

                            'x' => 190,
                            'y' => 84,
                        )
                    )
                ),
                '14' => array(
                    'w' => 720,
                    'h' => 558,
                    'frames' => array(
                        array(
                            'w' => 431,
                            'h' => 419,

                            'x' => 171,
                            'y' => 68,
                        )
                    )
                ),
                '13' => array(
                    'w' => 720,
                    'h' => 480,
                    'frames' => array(
                        array(
                            'w' => 475,
                            'h' => 426,

                            'x' => 38,
                            'y' => 31,
                        )
                    )
                ),
                '12' => array(
                    'w' => 720,
                    'h' => 540,
                    'frames' => array(
                        array(
                            'w' => 701,
                            'h' => 521,

                            'x' => 10,
                            'y' => 10,
                        )
                    )
                ),
                '11' => array(
                    'w' => 720,
                    'h' => 480,
                    'frames' => array(
                        array(
                            'w' => 366,
                            'h' => 353,

                            'x' => 40,
                            'y' => 38,
                        )
                    )
                ),
                '10' => array(
                    'w' => 720,
                    'h' => 511,
                    'frames' => array(
                        array(
                            'w' => 196,
                            'h' => 235,

                            'x' => 70,
                            'y' => 90,
                        ),
                        array(
                            'w' => 196,
                            'h' => 235,

                            'rotate' => 25,

                            'x' => 240,
                            'y' => 218,
                        ),
                        array(
                            'w' => 196,
                            'h' => 235,

                            'rotate' => 342,

                            'x' => 468,
                            'y' => 3,
                        )
                    )
                ), 
                '9' => array(
                    'w' => 720,
                    'h' => 507,
                    'frames' => array(
                        array(
                            'w' => 361,
                            'h' => 338,
                            'rotate' => 5,
                            'x' => 260,
                            'y' => 70,
                        )
                    )
                ),
                '8' => array(
                    'w' => 720,
                    'h' => 509,
                    'frames' => array(
                        array(
                            'w' => 250,
                            'h' => 340,
                            'rotate' => -37,
                            'x' => 165,
                            'y' => 30,
                        )
                    )
                ),
                '7' => array(
                    'w' => 720,
                    'h' => 509,
                    'frames' => array(
                        array(
                            'w' => 490,
                            'h' => 395,

                            'x' => 110,
                            'y' => 78,
                        )
                    )
                ), 
                '6' => array(
                    'w' => 720,
                    'h' => 514, 
                    'frames' => array(
                        array(
                            'w' => 590,
                            'h' => 440,

                            'x' => 50,
                            'y' => 12,
                        )
                    )
                ), 
                '5' => array(
                    'w' => 720,
                    'h' => 483,
                    'frames' => array(
                        array(
                            'w' => 294,
                            'h' => 394,

                            'x' => 222,
                            'y' => 57,
                        )
                    )
                ),
                '4' => array(
                    'w' => 720,
                    'h' => 507,
                    'frames' => array(
                        array(
                            'w' => 559,
                            'h' => 457,

                            'x' => 113,
                            'y' => 25,
                        )
                    )
                ),
                '3' => array(
                    'w' => 720,
                    'h' => 535,
                    'frames' => array(
                        array(
                            'w' => 555,
                            'h' => 483,

                            'x' => 166,
                            'y' => 0,
                        )
                    )
                ),
                '2' => array(
                    'w' => 720,
                    'h' => 480,
                    'frames' => array(
                        array(
                            'w' => 353,
                            'h' => 295,

                            'x' => 340,
                            'y' => 46,
                        )
                    )
                ),
                '1' => array(
                    'w' => 720,
                    'h' => 483,
                    'frames' => array(
                        array(
                            'w' => 497,
                            'h' => 407,

                            'x' => 130,
                            'y' => 77,
                        )
                    )
                ),

            );
            if($frame_key) return $frames[$frame_key];
            return $frames;
        }

        /**
        * Lists all models.
        */
        public function actionIndex()
        {
            if($success = Yii::app()->user->getFlash('success')){
                list($album, $photo) = json_decode($success, TRUE);
                $this->render('step4', array(
                        'album' => $album,
                        'photo' => $photo
                    ));
                Yii::app()->end();
            }

            $facebook = new Facebook(array(
                'appId'  => Yii::app()->params->user['fb']['appId'],
                'secret' => Yii::app()->params->user['fb']['secret'],
            ));
            $fb_id = $facebook->getUser();
            if(!$fb_id){                               
                $user_config = require(Yii::app()->basePath.'/modules/fbuser/config/main.php');
                $loginUrl = $facebook->getLoginUrl(array(
                        'scope' => $user_config['scope'],
                        'redirect_uri' => $this->createAbsoluteUrl('/anhhanquoc'),
                    ));
                $this->redirect($loginUrl);
            }

            if($_SERVER['REQUEST_METHOD'] == 'GET'){
                $this->_fb_step1($facebook);
            }elseif(isset($_POST['frame'])){
                $this->_fb_step2($facebook);   
            }elseif(isset($_POST['crop1'])){
                $this->_fb_step3();   
            }elseif(isset($_POST['crop2'])){
                $this->_fb_step4($facebook);   
            }
        }

        private function _fb_step1($facebook){
//            $likes = $facebook->api('/me/likes/342932269123960');
//            if(!$likes['data']){
//                $this->render('step0');
//                Yii::app()->end();
//            }


            $frames = $this->_getFrameData();

            $this->render('step1', array(
                    'frames' => $frames
                ));
            Yii::app()->end();
        }


        private function _fb_step2($facebook){
            Yii::app()->request->cookies['frame'] = new CHttpCookie('frame', $_POST['frame'], array('expire' => time()+3600*24*180));
            $frame = $this->_getFrameData($_POST['frame']);
            $frame_count = count($frame['frames']);

            $photos = $facebook->api( array(
                    'method' => 'fql.query',
                    'query' => "SELECT src, src_big, src_big_width, src_big_height, images from photo WHERE owner = me() ORDER BY rand() LIMIT 200",
                ));

            $this->render('step2', array(
                    'photos' => $photos, 
                    'frame_count' => $frame_count, 
                    'frame' => $_POST['frame'], 
                ));
            Yii::app()->end();
        }

        private function _fb_step3(){

            $path_temp = "files/images/frame/crop_1/";
            $frame = $this->_getFrameData(Yii::app()->request->cookies['frame']->value);

            $uploads = array();
            foreach($_POST['image'] as $i => $img){
                $upload = Myext::uploadImage($img, $path_temp, uniqid(), array(
                        'image_resize'              => true,
                        'image_ratio'               => true,
                        'image_x'                   => 720,
                        'image_y'                   => 960,
                        'jpeg_quality'                   => 100,
                    ));
                $upload->min_wh = $frame['frames'][$i];
                $upload->image = str_replace('\\','', $upload->file_dst_pathname);
                $uploads[] = $upload;
            }

            $this->render('step3', array(
                    'uploads' => $uploads, 
                ));
            Yii::app()->end();
        }

        private function _fb_step4($facebook){
            Yii::import('ext.imageLib');
            $frame_name = Yii::app()->request->cookies['frame']->value;
            $frame = $this->_getFrameData($frame_name);

            $path_temp = "files/images/frame/crop_2/";
            $crop2_images = array();
            $layer_name = '';
            foreach($_POST['x'] as $i => $x){
                $crop = array(
                    'image' => $_POST['image'][$i],
                    'l' => $x,
                    't' => $_POST['y'][$i],
                    'r' => $_POST['image_w'][$i] - $_POST['w'][$i] - $x,
                    'b' => $_POST['image_h'][$i] - $_POST['h'][$i] - $_POST['y'][$i],
                );
                $path = pathinfo($crop['image']);
                $upload = Myext::uploadImage($crop['image'], $path_temp, $path['filename'], array(
                        'image_crop'               => "{$crop['t']} {$crop['r']} {$crop['b']} {$crop['l']}",   // T R B L
                        'image_convert'             => 'png',
                        'jpeg_quality'                   => 100,
                    ));   
                $upload_image = str_replace('\\','', $upload->file_dst_pathname);
                $upload = Myext::uploadImage($upload_image, $path_temp, $path['filename'], array(
                        'image_resize'              => true,
                        'image_ratio'               => true, 
                        'image_x'                   => $frame['frames'][$i]['w'],
                        'image_y'                   => $frame['frames'][$i]['h'],
                        'image_convert'             => 'png',
                        'jpeg_quality'                   => 100,
                    ));

                if(isset($frame['frames'][$i]['rotate'])){
                    $magicianObj = new imageLib($upload_image);
                    $magicianObj->rotate($frame['frames'][$i]['rotate']);
                    $magicianObj->saveImage($upload_image, 100);
                }

                $crop2_images[] = $upload_image;
                $layer_name = $upload->file_dst_name_body;
            }

            $layer = "files/images/frame/frame/{$frame_name}_frame.png";
            $done_path = 'files/images/frame/done/';

            //        foreach($crop2_images as $i => $img){
            //            $upload = Myext::uploadImage($layer, $layer_path, '1', array(
            //                'image_watermark_x'                => $frame['frames'][$i]['x'],
            //                'image_watermark_y'                => $frame['frames'][$i]['y'],
            //                'image_watermark'             => $img,
            //            )); 
            //            $layer = str_replace('\\','', $upload->file_dst_pathname);
            //        }

            $imglayer = new imageLib($layer);
            foreach($crop2_images as $i => $img){
                $imglayer->addWatermark($img, "{$frame['frames'][$i]['x']} x {$frame['frames'][$i]['y']}");
            }
            $imglayer->saveImage($done_path.$layer_name.'.jpg', 100);

            $upload = Myext::uploadImage($done_path.$layer_name.'.jpg', $done_path, $layer_name, array(
                    'image_watermark'             => $layer,
                ));    


            $image = str_replace('\\','', $upload->file_dst_pathname);

            // create album
            $album_name = 'Ảnh Hàn Quốc';

            $albums = $facebook->api( array(
                    'method' => 'fql.query',
                    'query' => "SELECT aid, object_id, name, link, cover_pid, cover_object_id, photo_count FROM album WHERE owner = me()",
                ));

            $album = NULL;
            foreach($albums as $ab){
                if(mb_strtolower($ab['name'], 'UTF-8') == mb_strtolower($album_name, 'UTF-8')){
                    $album = $ab;
                    break;    
                }
            }

            if(!$album){
                $album = $facebook->api('/me/albums', 'post', array(
                        'message'=> $album_name.': anhhanquoc.hehe.vn',
                        'name'=> $album_name
                    ));
                $albums = $facebook->api( array(
                        'method' => 'fql.query',
                        'query' => "SELECT aid, object_id, name, link, cover_pid, cover_object_id, photo_count FROM album WHERE object_id = {$album['id']}",
                    ));
                $album = $albums[0];
            }

            // post photos to album
            
            $title = Yii::app()->request->getPost('title');
            
            $photo = $facebook->api("/{$album['object_id']}/photos", 'POST', array(
                    'source' => "@".realpath($image),
                    'message' => ($title ? "{$title} \n" : '') . "http://AnhHanQuoc.HeHe.vn",
                ));

            $ki = new KoreaImage;
            $ki->user_id = $this->user->id;
            $ki->fb_photo_id = $photo['id'];
            $ki->created = MyDateTime::getCurrentTime();
            $ki->setIsNewRecord(TRUE);
            $ki->insert();

            $photos = $facebook->api( array(
                    'method' => 'fql.query',
                    'query' => "SELECT object_id, src, src_big, link FROM photo WHERE object_id = {$photo['id']}",
                ));
            $photo = $photos[0];
            $photo['name'] = "{$frame['name']}";


            Yii::app()->user->setFlash('success', json_encode(array($album, $photo)));
            $this->refresh();


            //        $this->render('step4', array( 
            //            'album' => $album,  
            //            'photo' => $photo,  
            //        ), true);
            //        Yii::app()->end();
        }


    }
